<template>
  <div class="col center">
    <h2>{{ title }}</h2>
  </div>
  <Editor
    style="height: 500px; overflow-y: hidden"
    v-model="valueHtml"
    :defaultConfig="editorConfig"
    :mode="mode"
    @onCreated="handleCreated"
  />
  <div style="display: flex; flex-direction: column; align-items: start">
    <el-link
      target="_blank"
      v-for="file in fileList"
      :href="file.url"
      :key="file.url"
    >
      {{ file.name }}
    </el-link>
  </div>
</template>
<script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor } from '@wangeditor/editor-for-vue'

export default {
  components: { Editor },
  setup() {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    // 内容 HTML
    const valueHtml = ref('')
    const fileList = ref()
    const title = ref()
    onMounted(() => {})

    const editorConfig = {}
    editorConfig.readOnly = true

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    const setArticle = (article) => {
      console.log(article.content)
      title.value = article.title
      valueHtml.value = article.content
      fileList.value = eval(JSON.parse(JSON.stringify(article.attachment)))
    }

    return {
      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      editorConfig,
      handleCreated,
      setArticle,
      title,
      fileList,
    }
  },
}
</script>
